package com.itao.rocketmq5.delay;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.itao.rocketmq5.util.RocketMqFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.producer.SendReceipt;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @Author sjt
 * @CreateTime 2023/10/10 14:12
 */
@Slf4j
public class DelayProducer {

    private final static String DELAY_TOPIC = "delay_topic";

    public static void main(String[] args) {
        var producer = RocketMqFactory.getProducer(DELAY_TOPIC);
        // 延时1min
        var date = DateUtil.offset(new Date(), DateField.MINUTE, 1);
        log.info("当前时间:{}", date);
        var time = date.getTime();
        var message = RocketMqFactory.provider().newMessageBuilder()
                .setKeys("delayTopicKey")
                .setTag("delayTopic")
                .setTopic(DELAY_TOPIC)
                // 设置消息的延迟时间戳
                .setDeliveryTimestamp(time)
                .setBody("delayTopicMessage".getBytes(StandardCharsets.UTF_8))
                .build();
        try {
            //发送消息，需要关注发送结果，并捕获失败等异常。
            SendReceipt sendReceipt = producer.send(message);
            log.info("SendReceipt:{}", sendReceipt);
        } catch (ClientException e) {
            log.error("异常", e);
        }
    }
}
